%{
AUTHOR: Felipe Arteaga
-------------------------------------------------------------------------
PROJECT: Warnings
-------------------------------------------------------------------------
DESCRIPTION:
El periodo de analisis es desde que se mando (
05-Sep-2020 23:35:58 UTC  para el resto) y que se manda el SMSImagen con mienduc
(07-Sep-2020 19:40:48, UTC). O sea una ventana de 1 dia y 20 horas

=========================================================================
%}


clearvars -except projectDir projectDirData fromMainWarningsPaper
clc;close all;fclose('all');feature('DefaultCharacterSet','UTF-8');

if(not(exist('projectDir','var')==1&&exist('projectDirData','var')==1&&exist('fromMainWarningsPaper','var')==1&&fromMainWarningsPaper))
    pcName=char(java.lang.System.getProperty('user.name'));
    if(strcmp(pcName,'felipe'))
        % PC Felipe
        myDir='/Users/felipe/Dropbox/';
        projectDir=[myDir,'git/warnings/'];
        projectDirData=[myDir,'projects/warnings/'];
        addpath(genpath([myDir,'/myMatlabFunctions/']));
    end
end
compileLatexTable=false;

%%
dirPlots=[projectDir,'/paper/figuresCL/RDs/'];
dirTable=[projectDir,'/paper/tablesCL/'];

saveFigFile=false;
withPlot=true;

witCartillaSample=true;

%% Load data:

anho=2021;
anhoStr=sprintf('%i',anho);


load([projectDirData,'data/chile/',anhoStr,'/dataRD_RCT'],'dataRD','dataAppl','cortes')

sets=stataCollapse('id_consulta',dataAppl,'rbd','set');

sets=renamevars(sets,{'id_consulta','rbd_set'},{'idConsultaPreW','rbd_preW'});
dataRD=outerjoin(dataRD,sets,'keys',{'idConsultaPreW'},'mergeKeys',true,'type','left');

sets=renamevars(sets,{'idConsultaPreW','rbd_preW'},{'idConsultaEnd','rbd_end'});
dataRD=outerjoin(dataRD,sets,'keys',{'idConsultaEnd'},'mergeKeys',true,'type','left');

sets=renamevars(sets,{'idConsultaEnd','rbd_end'},{'idConsultaPreC6','rbd_preC6'});
dataRD=outerjoin(dataRD,sets,'keys',{'idConsultaPreC6'},'mergeKeys',true,'type','left');


dataRD.catRisk=discretize(dataRD.riskWhatsapp,[0,.2,.3,1],'Categorical','includedEdge','right');
dataRD.catTreat=double(dataRD.intendedWarningWhatsapp);
dataRD.catTreat(dataRD.riskWhatsapp<.2)=0;
dataRD.catTreat(dataRD.intendedWarningWhatsapp==1&dataRD.riskWhatsapp>.3)=2;
dataRD.catTreat=categorical(dataRD.catTreat,[0 1 2],{'Control','General','Personalized'});
tabflow(dataRD.catRisk,dataRD.catTreat,'minPercToPlot',0,'labels',{'Predicted Risk','Treatment'});

tabflow(dataRD.catRisk(dataRD.pobWhatsapp),dataRD.catTreat(dataRD.pobWhatsapp),'minPercToPlot',0,'labels',{'Predicted Risk','Treatment'});




%% Functions 

addAny=@(iniP,endP)any(not(ismember(endP,iniP)));
schoolsAdded=@(iniP,endP)length(endP)-length(iniP);


%% Calculations

dataRD.changeAnyPreWEnd=cellfun(@changeAny,dataRD.rbd_preW,dataRD.rbd_end);
dataRD.changeAnyPreWPreC6=cellfun(@changeAny,dataRD.rbd_preW,dataRD.rbd_preC6);


dataRD.addAnyPreWEnd=cellfun(addAny,dataRD.rbd_preW,dataRD.rbd_end);
dataRD.addAnyPreWPreC6=cellfun(addAny,dataRD.rbd_preW,dataRD.rbd_preC6);

dataRD.schoolsAddedPreWEnd=cellfun(schoolsAdded,dataRD.rbd_preW,dataRD.rbd_end);
dataRD.schoolsAddedPreWPreC6=cellfun(schoolsAdded,dataRD.rbd_preW,dataRD.rbd_preC6);

dataRD.DRiskExpostPreWEnd=dataRD.riesgoUltimaDiaEnd-dataRD.riesgoUltimaDiaPreW;
dataRD.DRiskExpostPreWPreC6=dataRD.riesgoUltimaDiaPreC6-dataRD.riesgoUltimaDiaPreW;

dataRD.rural=dataRD.newMarket<0;

%% RDs, OLSs and IVs
% Calls Stata to do all the inference, but it plots and creates tables in
% matlab.

% Restricion to all specifications
% -Only applicants with some level of risk. Ommit mass points at extremes
% -Sample of the RCT (pobWhatsapp)

restrToAll=dataRD.riskWhatsapp>0.01&dataRD.riskWhatsapp<0.99&dataRD.pobWhatsapp==1;
if(not(witCartillaSample))
    restrToAll=restrToAll&not(dataRD.intendedCartilla6Whatsapp);
end

subpobs=cell(1,3);
subpobs(1,:)={'All',            restrToAll,'all'};
% subpobs(2,:)={'w/cartilla',   restrToAll&(dataRD.intendedCartillaWhatsapp==1|dataRD.controlWhatsapp==1),'wC'};
% subpobs(3,:)={'wo/cartilla',      restrToAll&(dataRD.intendedCartillaWhatsapp==0|dataRD.controlWhatsapp==1),'woC'};
% subpobs(4,:)={'w/image simple',   restrToAll&(dataRD.typeImageWhatsapp==1|dataRD.controlWhatsapp==1|dataRD.riskWhatsapp<=.3),'wI1'};
% subpobs(5,:)={'w/image bar',      restrToAll&(dataRD.typeImageWhatsapp==2|dataRD.controlWhatsapp==1|dataRD.riskWhatsapp<=.3),'wI2'};
% subpobs(6,:)={'w/image seats',    restrToAll&(dataRD.typeImageWhatsapp==3|dataRD.controlWhatsapp==1|dataRD.riskWhatsapp<=.3),'wI3'};
%subpobs(7,:)={'Control WhatsApp',restrToAll&dataRD.controlWhatsapp==1};



%% Define outcomes (and table order)
% Use 4rd row if want to start a new panel
% Use 5th row to define is IV is relevant. .5 if IV is not relevant, but
% plot is
% Use 6th row to define YLim of plot...optional!
% Use 7th row to define the enodgenous var in IV

outcomes={'prioritario','Economically Vulnerable','sep','A. Balance',0,[0 1],'';...
    'rural','Rural','rur','',0,[0 .1],'';...
    'treatedWarningWhatsapp','WhatsApp read','fs_w','B. Message receipt',0,[-0.05 1],'';... % First stage of whatsapp intention over whatsapp read (moment right before SMSPlain was sent)
    'intendedCartilla6Whatsapp','Report card intention to treat','fs_rp','',0,[],'';... % First stage of whatsapp intention over Cartilla Claudia
    'changeAnyPreWPreC6','Any modification','am_preC6','C. Outcomes in clean 5 days before report card',0.5,[-.04 .2],'';...
    'addAnyPreWPreC6','Add any','aa_preC6','',0.5,[-.04 .16],'';...
    'schoolsAddedPreWPreC6','Schools Added','sa_preC6','',1,[-.04 .3],'addAnyPreWPreC6';...
    %'riskExpostPreW','True Risk pre whatsapp','trPreW','',1,[-.04 .03]; ...
    %'riskExpostPreSI','True Risk post whatsapp','trPreSI','',1,[-.04 .03]; ...
    'DRiskExpostPreWPreC6','$\Delta$ Risk','dr_preC6','',1,[-.06 .03],'addAnyPreWPreC6';...
    'changeAnyPreWEnd','Any modification','am','D. Endline outcomes',0.5,[-.04 .2],'';...
    'addAnyPreWEnd','Add any','aa','',0.5,[-.04 .16],'';...
    'schoolsAddedPreWEnd','Schools Added','sa','',1,[-.04 .3],'addAnyPreWEnd';...
    %'riskExpostPreW','True Risk pre whatsapp','trPreW','',1,[-.04 .03]; ...
    %'riskExpostPreSI','True Risk post whatsapp','trPreSI','',1,[-.04 .03]; ...
    'DRiskExpostPreWEnd','$\Delta$ Risk','dr','',1,[-.06 .03],'addAnyPreWEnd';...
    };


% Restriction to all
inAnyPob=restrToAll;

commands=cell(size(subpobs,1)*size(outcomes,1),2);
counter=1;




for p=1:size(subpobs,1)

        
        
        dataRD.(sprintf('subpop%i',p))=subpobs{p,2};
        
       
        
        for o=1:size(outcomes,1)
            
            % RCT Smart
            commands(counter,:)={sprintf('reg_itt_%s_%i_smart',outcomes{o,3},p),...
                sprintf('reg  %s intendedWarningWhatsapp if subpop%i==1&riskWhatsapp>.3, robust',outcomes{o,1},p)};counter=counter+1;
            
            if(outcomes{o,5}==1)
                
                commands(counter,:)={sprintf('reg_iv_%s_%i_smart',outcomes{o,3},p),...
                    sprintf('ivregress 2sls %s  (%s=intendedWarningWhatsapp) if subpop%i==1&riskWhatsapp>.3, first robust',outcomes{o,1},outcomes{o,7},p)};counter=counter+1;
            end
            
             
            % RCT Dumb
            commands(counter,:)={sprintf('reg_itt_%s_%i_dumb',outcomes{o,3},p),...
                sprintf('reg  %s intendedWarningWhatsapp if subpop%i==1&riskWhatsapp<=.3&riskWhatsapp>.2, robust',outcomes{o,1},p)};counter=counter+1;
            
            if(outcomes{o,5}==1)
                % TOT Dumb
                commands(counter,:)={sprintf('reg_iv_%s_%i_dumb',outcomes{o,3},p),...
                    sprintf('ivregress 2sls %s  (%s=intendedWarningWhatsapp) if subpop%i==1&riskWhatsapp<=.3&riskWhatsapp>.2, first robust',outcomes{o,1},outcomes{o,7},p)};counter=counter+1;
            end
            
            % RD Dumb
            
            commands(counter,:)={sprintf('rd_full_itt_%s_treated_%i_dumb',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&((riskWhatsapp<=.3&intendedWarningWhatsapp==1)|riskWhatsapp<.2), c(.2) p(2) h(.18 .1) kernel(uniform)',outcomes{o,1},p)};counter=counter+1;
            
            commands(counter,:)={sprintf('rd_full_itt_%s_control_%i_dumb',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&((riskWhatsapp<=.3&intendedWarningWhatsapp==0)|riskWhatsapp<.2), c(.2) p(2) h(.18 .1) kernel(uniform)',outcomes{o,1},p)};counter=counter+1;
            
            commands(counter,:)={sprintf('rd_local_itt_%s_%i_dumb',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&((riskWhatsapp<=.3&intendedWarningWhatsapp==1)|riskWhatsapp<.2), c(.2) h(.1 .1)',outcomes{o,1},p)};counter=counter+1;
            
            if(outcomes{o,5}==1)
                % TOT
                commands(counter,:)={sprintf('rd_local_iv_%s_%i_dumb',outcomes{o,3},p),...
                    sprintf('rdrobust %s riskWhatsapp if subpop%i==1&((riskWhatsapp<=.3&intendedWarningWhatsapp==1)|riskWhatsapp<.2), c(.2) h(.1 .1) fuzzy(%s)',outcomes{o,1},p,outcomes{o,7})};counter=counter+1;
            end
            
                      % RD Smart
            
            commands(counter,:)={sprintf('rd_full_itt_%s_treated_%i_smart',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&(riskWhatsapp>.2&intendedWarningWhatsapp==1), c(.3) p(2) h(.1 .68)',outcomes{o,1},p)};counter=counter+1;
            
            commands(counter,:)={sprintf('rd_full_itt_%s_control_%i_smart',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&(riskWhatsapp>.2&intendedWarningWhatsapp==0), c(.3) p(2) h(.1 .68)',outcomes{o,1},p)};counter=counter+1;
            
            commands(counter,:)={sprintf('rd_local_itt_%s_%i_smart',outcomes{o,3},p),...
                sprintf('rdrobust %s riskWhatsapp if subpop%i==1&(riskWhatsapp>.2&intendedWarningWhatsapp==1), c(.3) h(.1 .68)',outcomes{o,1},p)};counter=counter+1;
            
            if(outcomes{o,5}==1)
                % TOT
                commands(counter,:)={sprintf('rd_local_iv_%s_%i_smart',outcomes{o,3},p),...
                    sprintf('rdrobust %s riskWhatsapp subpop%i==1&(riskWhatsapp>.2&intendedWarningWhatsapp==1), c(.3) h(.1 .1) fuzzy(%s)',outcomes{o,1},p,outcomes{o,7})};counter=counter+1;
            end
            
        end
        
   
end



% This is OK, since subsamples in each reagression depend on the label of
% the var, not in the position of the observations.
dataRD=dataRD(inAnyPob,:);

%% RUN all the regs and rds in Stata
res=stataCommand(commands,dataRD,'selectcolumns',true);

%% Recover resutls and do tables/plots



cantPobs=(size(subpobs,1));
cantRegs=(size(outcomes,1));

% This is not "effective obs":
matrix_nl_t=nan(cantRegs,cantPobs);
matrix_nr_t=nan(cantRegs,cantPobs);

matrix_nl=nan(cantRegs,cantPobs);
matrix_nr=nan(cantRegs,cantPobs);
matrix_n=nan(cantRegs,cantPobs);

matrix_b=nan(cantRegs,4,2);
matrix_sd=nan(cantRegs,4,2);

matrix_pOrder=nan(cantRegs,cantPobs);
cell_pl=cell(cantRegs,cantPobs);
cell_pr=cell(cantRegs,cantPobs);


resStored=fieldnames(res);
close all


for p=1:cantPobs
    for r=1:cantRegs
        
        withIv=false;
        
        res_reg_i_s=res.(sprintf('reg_itt_%s_%i_smart',outcomes{r,3},p));
        res_rd_i_s=res.(sprintf('rd_local_itt_%s_%i_smart',outcomes{r,3},p));
        res_reg_i_d=res.(sprintf('reg_itt_%s_%i_dumb',outcomes{r,3},p));
        res_rd_i_d=res.(sprintf('rd_local_itt_%s_%i_dumb',outcomes{r,3},p));
        
        if(p==1&&r==1)
            nRCT_d=mat2cellstr(res_reg_i_d.N,'rc',true);
            nRCT_s=mat2cellstr(res_reg_i_s.N,'rc',true);
        end
        
        % If is outcome (not first stage neither balance), then recover IV:
        if(outcomes{r,5}==1)
            withIv=true;
            resIv_reg_i_s=res.(sprintf('reg_iv_%s_%i_smart',outcomes{r,3},p));
            resIv_rd_i_s=res.(sprintf('rd_local_iv_%s_%i_smart',outcomes{r,3},p));
            resIv_reg_i_d=res.(sprintf('reg_iv_%s_%i_dumb',outcomes{r,3},p));
            resIv_rd_i_d=res.(sprintf('rd_local_iv_%s_%i_dumb',outcomes{r,3},p));
        end
        
        
        %% RCT
        % Beta
        matrix_b(r,1,1)=res_reg_i_d.b(1,1);
        matrix_b(r,1,2)=res_reg_i_s.b(1,1);
        % Sd Beta
        matrix_sd(r,1,1)=sqrt(res_reg_i_d.V(1,1));
        matrix_sd(r,1,2)=sqrt(res_reg_i_s.V(1,1));
        % N
        %matrix_n(r,p)=res_reg_i.N;
        
        if(withIv)
            % Beta
            matrix_b(r,2,1)=resIv_reg_i_d.b(1,1);
            % Sd Beta
            matrix_sd(r,2,1)=sqrt(resIv_reg_i_d.V(1,1));
            % Beta
            matrix_b(r,2,2)=resIv_reg_i_s.b(1,1);
            % Sd Beta
            matrix_sd(r,2,2)=sqrt(resIv_reg_i_s.V(1,1));
        end
        
        
        %% RD
        % Beta
        matrix_b(r,3,1)=res_rd_i_d.tau_cl;
        % Sd Beta
        matrix_sd(r,3,1)=res_rd_i_d.se_tau_cl;
                % Beta
        matrix_b(r,3,2)=res_rd_i_s.tau_cl;
        % Sd Beta
        matrix_sd(r,3,2)=res_rd_i_s.se_tau_cl;
        
        
        % N
        %         matrix_nl(r,p)=res_i.N_h_l;
        %         matrix_nr(r,p)=res_i.N_h_r;
        %
        %         matrix_nl_t(r,p)=res_i.N_l;
        %         matrix_nr_t(r,p)=res_i.N_r;
        
        if(withIv)
            % Beta
            matrix_b(r,4,1)=resIv_rd_i_d.b(1,1);
            % Sd Beta
            matrix_sd(r,4,1)=sqrt(resIv_rd_i_d.V(1,1));
            
           matrix_b(r,4,2)=resIv_rd_i_s.b(1,1);
            % Sd Beta
            matrix_sd(r,4,2)=sqrt(resIv_rd_i_s.V(1,1));
        end
        
        % Bandwidth
        %matrix_nl(counter,p)=res.st(sirve);
        %matrix_nr(counter,p)=res.st(sirve);
        
        % Double RD (+ RCT)
        if(withPlot)
            
            
    
    
            % If I calculate IV means is an outcome, hence I wanna plot the
            % RD - RCT and not only the RD.
            plotRDControl=outcomes{r,5}>=.5;
            
            rdSmart=res.(sprintf('rd_full_itt_%s_treated_%i_smart',outcomes{r,3},p));
            rdSmart_c=res.(sprintf('rd_full_itt_%s_control_%i_smart',outcomes{r,3},p));
            rdDumb=res.(sprintf('rd_full_itt_%s_treated_%i_dumb',outcomes{r,3},p));
            rdDumb_c=res.(sprintf('rd_full_itt_%s_control_%i_dumb',outcomes{r,3},p));
            
            rdSmart_local=res.(sprintf('rd_local_itt_%s_%i_dumb',outcomes{r,3},p));
            rdDumb_local=res.(sprintf('rd_local_itt_%s_%i_dumb',outcomes{r,3},p));
            
            rct_smart=res_reg_i_s;
            rct_dumb=res_reg_i_d;
            
       
            colorC=[0 0.4470 0.7410];
            colorTS=[0.6350 0.0780 0.1840];
            colorTD=[75	125	75]/256;
            
            % Plot treatments:
            figure
            %Smart, plotting only right scatter and only right fit
            fS=plotRD(rdSmart,dataRD,'subpop',dataRD.riskWhatsapp>.2&dataRD.intendedWarningWhatsapp==1&dataRD.(sprintf('subpop%i',p)),'posBeta',.8,'color',colorTS,'posBetaHorz',.13,'withcutoffverticalline',false,'marker','o','parameterLabel','\beta_{RD-perso.}','withLeftScatter',false,'modifyPlotLims',false,'otherpointestimate',rdSmart_local,'withLeftRDFit',false,'withStars',false);% 'otherpointestimate',res_rd_i_control_local
            hold on
            % Dumb, plotting only right scatter and only right fit
            fD=plotRD(rdDumb,dataRD,'subpop',dataRD.riskWhatsapp<=.3&(dataRD.riskWhatsapp<.2|dataRD.intendedWarningWhatsapp==1)&dataRD.(sprintf('subpop%i',p)),'posBeta',.5,'color',colorTD,'withcutoffverticalline',false,'marker','d','parameterLabel','\beta_{RD-gener.}','withLeftScatter',false,'modifyPlotLims',false,'otherpointestimate',rdDumb_local,'withLeftRDFit',false,'withStars',false);%
            xlim([0 1])
            
            
            % Plot controls:
            %Smart, plotting only right scatter and only right fit
            fS_c=plotRD(rdSmart_c,dataRD,'subpop',dataRD.riskWhatsapp>.2&dataRD.intendedWarningWhatsapp==0&dataRD.(sprintf('subpop%i',p)),'color',colorC,'withcutoffverticalline',false,'marker','x','parameterLabel','\beta_{RD\_C}','withLeftScatter',true,'modifyPlotLims',false,'posBeta',.5,'otherpointestimate',rdDumb_local,'withpointestimate',0,'withLeftRDFit',false);% 'otherpointestimate',res_rd_i_control_local
            hold on
            % Dumb, plotting right and left scatter (fit with uniform kernel)
            fD_c=plotRD(rdDumb_c,dataRD,'subpop',dataRD.riskWhatsapp<=.3&(dataRD.riskWhatsapp<.2|dataRD.intendedWarningWhatsapp==0)&dataRD.(sprintf('subpop%i',p)),'color',colorC,'withcutoffverticalline',false,'marker','x','parameterLabel','\beta_{RD\_C}','withRightScatter',false,'modifyPlotLims',false,'posBeta',.5,'withpointestimate',0);% 'otherpointestimate',res_rd_i_control_local
            
            
            % Plot ITT
            
            annotation('textbox',[.13 .7 .1 .1],'String',sprintf('$ITT_{RCT-perso.}: %.3f$\n$\\quad\\quad\\quad\\quad(%.3f)$',rct_smart.b(1,1),sqrt(rct_smart.V(1,1))),'FitBoxToText','on','Interpreter','latex','edgecolor','none','color',colorTS);
            annotation('textbox',[.13 .4 .1 .1],'String',sprintf('$ITT_{RCT-gener.}: %.3f$\n$\\quad\\quad\\quad\\quad(%.3f)$',rct_dumb.b(1,1),sqrt(rct_dumb.V(1,1))),'FitBoxToText','on','Interpreter','latex','edgecolor','none','color',colorTD);
            

            
            hold on
            maxY=1;
            plot(.2*[1 1],[0 maxY],'--','color',.5*[1 1 1])
            plot(.3*[1 1],[0 maxY],'--','color',.5*[1 1 1])
            hold off
            % Add legend and ITT of RCT result:
            legend([fS_c.binscatter_l.scatter fD.binscatter_r.scatter fS.binscatter_r.scatter],{'No treatment','General risk information','Personalized risk information'},'Interpreter','latex','Location','NorthEast');
            %legend boxoff


            if(not(isempty(outcomes{r,6})))
                ylim(outcomes{r,6});
            end
            
            xlim([0 1])
         

            xlabel('Predicted placement risk')
            ylabel(outcomes{r,2})
            if(witCartillaSample)
            easyExport([dirPlots,sprintf('%s_Whatsapp_%s_%s.png',anhoStr,outcomes{r,3},subpobs{p,3})],'width',650,'height',250);
            else
              easyExport([dirPlots,sprintf('%s_Whatsapp_%s_%s_withoutCartillaSample.png',anhoStr,outcomes{r,3},subpobs{p,3})],'width',650,'height',250);  
            end
            
            if(saveFigFile)
                savefig(sprintf('%sW_%s_%s',dirPlots,outcomes{r,3},subpobs{p,3}))
            end
            
            
        end
    end
end





%%

posPan=find(not(cellfun(@isempty,outcomes(:,4))));
panel=[num2cell(posPan-1),outcomes(posPan,4)];



head=[repmat({'General risk information'},1,4),repmat({'Personalized risk information'},1,4);...
    {'RCT','RCT','RD','RD','RCT','RCT','RD relative to','RD relative to';'','','','','','','general risk treatm.','general risk treatm.';'ITT','IV','ITT','IV','ITT','IV','ITT','IV'}];
matTable=[matrix_b(:,:,1),matrix_b(:,:,2)];
matTable_sd=[matrix_sd(:,:,1),matrix_sd(:,:,2)];
opt=struct;

%nRD=mat2cellstr(1000,'rc',true);
opt.note="ITT and IV effects of 2021 WhatsApp warnings intervention. RCT columns (1) and (2): effects of random assignment to general risk information message vs. control group for students with predicted risk $\in (.2,.3]$. RCT columns (5) and (6): effects of random assignment to personalized risk information message vs. control group for students with predicted risk $>.3$. Robust SEs in parentheses. General information intervention N="+nRCT_d+".  Personalized information intervention N="+nRCT_s+". "+...
    "RD columns (3) and (4): regression discontinuity evaluation of general risk information message vs no treatment around 0.20 cutoff. RD columns (7) and (8): regression discontinuity evaluation of personalized risk information message vs general risk information message around 0.30 cutoff. RD specifications computed using local linear fit with a bandwidth of 0.1. "+...
    "Standard errors are heteroskedasticity-robust nearest neighbor variance estimator with minimum of 3 neighbors, as in \citet{calonico2014robust}. ITT column shows effects of group assignment. IV columns show the instrumental variable specification, where the endogenous regressor is the add any school indicator, instrumented with group assignment for the RCT, and with a dummy of crossing the risky threshold for the RD. "+...
    "Panel A: balance tests on predetermined characteristics. Panel B: message receipt. ``WhatsApp read'' is an indicator equal to one if applicant views the WhatsApp treatment message. ``Report card intention to treat'' is indicator for receiving a report card 5 days later. Report card included additional information on nonplacement probability and school options. 28% of the RCT sample were assigned to received the report card. Panel C: outcomes within 5 days window between WhatsApp intervention and report card was sent.  Panel D: endline choice behavior. See the description of the 2021 intervention in section \ref{app:int} for details.  ";
opt.header=head;
opt.stderrs=mat2cellstr(matTable_sd,'conParentesis',true,'precisionDecimal','%.3f');
%opt.stars=getStars(matTable,matTable_sd);
opt.primeracolumna=outcomes(:,2);%[regressions(:,1);{'N'};regressions(:,1);{'NL';'NR'}];
opt.addColumnNumber=true;
opt.columnafantasma=[ 4 ];
opt.adjust=true;
opt.panel=panel;
opt.positionParameter='H';
opt.sizeFootnoteFloat='\scriptsize';
opt.verticalAdjustParam=14;
if(witCartillaSample)
    opt.title='WhatsApp RD and RCT Results -- 2021 ';
    opt.label='tab:RCT2021';
    opt.file=sprintf('%s%itableWhatsapp',dirTable,anho);
else
    opt.title='WhatsApp RD and RCT Results -- 2021 -- WITHOUT REPORT CARD SAMPLE';
    opt.label='tab:RCT2021-woCartillaSample';
    opt.file=sprintf('%s%itableWhatsapp_withoutCartillaSample',dirTable,anho);

end
tabla=cell2latex(mat2cellstr(matTable,'precisionDecimal','%.3f','revisarFilas',true),'opts',opt);
if(compileLatexTable)
compileLatex(tabla)
end


function ca=changeAny(iniP,endP)
ca=true;
 if(length(iniP)==length(endP))
     ca=any(not(iniP==endP));
 end
end